package com.lagou.transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author zhengzc
 * @version 1.0.0
 * @date 2020/2/24 20:00
 */
public class JdbcTransaction implements Transaction {

    protected Connection connection;
    protected DataSource dataSource;
    protected boolean autoCommit;

    public JdbcTransaction(DataSource ds,boolean desiredAutoCommit) {
        this.dataSource = ds;
        this.autoCommit = desiredAutoCommit;
    }
    @Override
    public Connection getConnection() throws SQLException {
        if (this.connection == null) {
            this.openConnection();
        }
        return this.connection;
    }

    @Override
    public void commit() throws SQLException {
        if (this.connection != null && !this.connection.getAutoCommit()) {
            this.connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (this.connection != null && !this.connection.getAutoCommit()) {
            this.connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (this.connection != null) {
            this.resetAutoCommit();
            this.connection.close();
        }
    }

    protected void resetAutoCommit() {
        try {
            if (!this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(true);
            }
        } catch (SQLException e) {
            System.out.println("Error resetting autocommit to true before closing the connection!");
            e.printStackTrace();
        }

    }

    protected void openConnection() throws SQLException {
        this.connection = this.dataSource.getConnection();
        this.setDesiredAutoCommit(this.autoCommit);
    }

    protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
        try {
            if (this.connection.getAutoCommit() != desiredAutoCommit) {
                this.connection.setAutoCommit(desiredAutoCommit);
            }

        } catch (SQLException e){
            e.printStackTrace();
        }
    }
}
